<template>
  <contentModel
    title="详情"
    :class="screenClass"
    :has-footer="false"
    @close="cancel"
    @open="modalOpen"
  >
    <query-form
      :component-config="formComponentConfig"
      :render-config="formRenderConfig"
      :render-keys="detailRenderKeys"
      @search="searchHandle"
      @reset="resetHandle"
    />
    <sub-title>到货箱单信息</sub-title>
    <table-container
      v-model:columns="columns"
      v-model:is-fullscreen="isFullscreen"
      :loading="boxTableLoading"
      :all-columns="allColumns"
      @refresh="getBoxTableList"
    >
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['pms:receive-box:save']"
            type="primary"
            @click="addBox"
            >新增</a-button
          >
        </a-space>
      </template>
      <standard-table
        ref="boxTable"
        v-model:selectedKeys="boxSelectedKeys"
        :component-config="tableComponentConfig"
        :render-config="tableRenderConfig"
        :render-keys="tableRenderBoxKeys"
        :loading="boxTableLoading"
        :data="boxTableData"
        :total="boxTableTotal"
        :columns="columns"
        row-selection-type="radio"
        @init-columns-end="initColumns"
        @selection-change="boxSelectionChange"
        @page-change="boxPageChange"
        @page-size-change="boxPageSizeChange"
      >
        <template #operate="{ record, rowIndex }">
          <a-button
            v-permission="['pms:receive-box:update']"
            type="text"
            @click="editBox(record, rowIndex)"
            >编辑</a-button
          >
          <a-button
            v-permission="['pms:receive-box:delete']"
            type="text"
            @click="deleteBox(record, rowIndex)"
            >删除</a-button
          >
        </template>
      </standard-table>
    </table-container>
    <sub-title>到货订单信息</sub-title>
    <div style="padding: 16px 0">
      <a-space>
        <a-button
          v-permission="['pms:receive-detail:saveReceiveDetailAll']"
          type="primary"
          @click="addDetail"
          >新增</a-button
        >
        <a-button
          v-permission="['pms:receive:arrivalConfirmation']"
          type="primary"
          :disabled="!detailSelectedKeys.length"
          :loading="confirmationLoading"
          @click="confirmation"
          >到货确认</a-button
        >
      </a-space>
    </div>
    <standard-table
      ref="detailTable"
      v-model:selectedKeys="detailSelectedKeys"
      :component-config="tableComponentConfig"
      :render-config="tableRenderConfig"
      :render-keys="detailTableRenderKeys"
      :loading="detailTableLoading"
      :data="detailTableData"
      :total="detailTableTotal"
      height="400px"
      row-selection-type="checkbox"
      @selection-change="detailSelectionChange"
      @page-change="detailPageChange"
      @page-size-change="detailPageSizeChange"
    >
      <template #operate="{ record, rowIndex }">
        <a-button
          v-permission="['pms:receive-detail:delete']"
          type="text"
          @click="deleteDetail(record, rowIndex)"
          >删除</a-button
        >
      </template>
    </standard-table>
  </contentModel>
  <AddSupplierModel
    v-if="addSupplierModelVisible"
    v-model="addSupplierModelVisible"
    :pms-receive-id="selectId"
    :select-id="selectBoxId"
    @fetch-data="getBoxTableList"
  ></AddSupplierModel>
  <SelectOrderModal
    v-if="selectOrderModelVisible"
    v-model="selectOrderModelVisible"
    :pms-receive-id="selectId"
    :select-id="selectDetailId"
    :box-select-id="boxSelectedKeys"
    @fetch-data="getDetailTableList"
  ></SelectOrderModal>
</template>

<script lang="ts" setup>
  import { defineAsyncComponent, ref, toRefs } from 'vue';
  import queryForm from '@/common/components/query-form/index.vue';
  import standardTable from '@/common/components/standard-table/index.vue';
  import TableContainer from '@/common/components/table-container/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { info } from '@/common/utils/modal-promise';
  import useFullScreen from '@/common/hooks/fullScreen';
  import {
    getPmsReceiveBoxPage,
    getPmsReceiveDetailPage,
    deletePmsReceiveBox,
    deletePmsReceiveDetail,
    arrivalConfirmation,
  } from '@/api/purchaseArrival/arrivalRegistration';
  import lodash from 'lodash';
  import subTitle from '@/common/components/title/sub-title.vue';
  import { hasDataAndBack } from '@/common/utils';
  // import { Message } from '@arco-design/web-vue';
  import {
    formComponentConfig,
    formRenderConfig,
  } from '../moduleCommon/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../moduleCommon/tableComp/baseTableConfig';

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const AddSupplierModel = defineAsyncComponent(
    () => import('./AddSupplierModel.vue')
  );
  const SelectOrderModal = defineAsyncComponent(
    () => import('./SelectOrderModal.vue')
  );
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    // eslint-disable-next-line vue/require-prop-types
    selectId: {},
  });
  const emits = defineEmits(['update:modelValue']);
  const cancel = () => {
    emits('update:modelValue', false);
  };
  const { isFullscreen, screenClass } = useFullScreen();
  const { selectId } = toRefs(props);
  // const { cancel } = useModelFun();
  // const loading = ref(false);
  const addSupplierModelVisible = ref(false);
  const confirmationLoading = ref(false);
  const selectBoxId = ref(null);
  const selectDetailId = ref(null);
  const addBox = () => {
    selectBoxId.value = null;
    addSupplierModelVisible.value = true;
  };
  const editBox = (row) => {
    selectBoxId.value = row.id;
    addSupplierModelVisible.value = true;
  };
  const getDetailInfo = async () => {
    getBoxTableList();
    getDetailTableList();
  };
  const modalOpen = () => {
    if (boxTableLoading.value) return;
    if (selectId?.value) {
      boxTableLoading.value = true;
      getDetailInfo();
    } else {
      boxTableLoading.value = false;
    }
  };
  const confirmation = async () => {
    if (!detailSelectedKeys.value.length) {
      Message.info({
        content: '请选择到货订单！',
        duration: 5 * 1000,
      });
      return;
    }
    await info({
      title: '到货确认',
      content: '您确定要到货确认当前所选的数据？',
      okText: '确认',
    });
    try {
      confirmationLoading.value = true;
      await arrivalConfirmation(detailSelectedKeys.value);
      detailSelectedKeys.value = [];
      Message.success({
        content: '到货确认成功！',
        duration: 5 * 1000,
      });
      getDetailTableList();
    } finally {
      confirmationLoading.value = false;
    }
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  let boxSelectRowList: Array<any> = [];
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  let detailSelectRowList: Array<any> = [];
  // 当前表格要渲染哪些值
  const tableRenderBoxKeys = [
    'secretLevel',
    'packageNo',
    'invoiceNo',
    'deliverAddress',
    'deliverDate',
    'packageVolume',
    'netWeight',
    'grossWeight',
    'freightFee',
    'insuranceFee',
    'otherFee',
    'totalFee',
    'goodsAmount',
    'currencyType',
    'transportType',
    'receiveOrder',
    'receiveAddress',
    'receiveUserCode',
    'receiveDate',
    'operate',
  ];
  const detailTableRenderKeys = [
    'secretLevel',
    'dataSourceType', // 数据来源
    'orderNo2',
    'sysOrderNo',
    'serialNo',
    'mdsItemCode',
    'mdsItemName',
    'modelMark', // 牌号
    'specification', // 规格
    'figureNumber', // 图号
    'jishutiaojian', // 技术条件
    'invDeliverQty3',
    'pmsDeliverQty3',
    'cwxhsl', // 厂外消耗数量
    'invoiceNo',
    'proMdsItemCode',
    'sendDate',
    'itemManufactureFactoryName',
    'itemManufactureFactoryCode',
    'dealerName',
    'dealerCode',
    'pmsPredictPrice',
    'deliverType',
    'itemState',
    'qualityFile',
    'sparePart',
    'instructions',
    'itemSerialNo',
    'urgencyDegree',
    'xtfhxlh', // 协同发货序列号
    'planSourceType',
    'operate',
  ];
  // select-order
  const selectOrderModelVisible = ref(false);
  // detail-list
  const detailTable = ref(null);
  const detailRenderKeys = [
    'sysOrderNo',
    'mdsItemCode',
    'mdsItemName',
    'modelMark',
    'figureNumber',
  ];
  const detailSelectedKeys = ref([]);

  const detailTableLoading = ref(false);
  const detailTableData = ref([]);
  const detailTableTotal = ref(0);
  const searchHandle = (query = {}) => {
    getDetailTableList(query);
  };
  const resetHandle = () => {
    getDetailTableList({});
  };
  const detailSelectionChange = (rowKeys: (string | number)[]) => {
    if (rowKeys && rowKeys.length) {
      detailSelectRowList = rowKeys;
      // const [selectId] = detailSelectRowList;
      // selectDetailId.value = selectId;
    }
  };
  const columns = ref<object[]>([]);
  const allColumns = ref<object[]>([]);
  const initColumns = (data: any[]) => {
    columns.value = lodash.cloneDeep(data);
    allColumns.value = lodash.cloneDeep(data);
  };
  const detailPageChange = () => {
    getDetailTableList();
  };
  const detailPageSizeChange = () => {
    getDetailTableList();
  };
  const getDetailTableList = async (query = {}) => {
    query.pmsReceiveId = selectId?.value;
    const page = detailTable.value.getStatus();
    detailTableLoading.value = true;
    const { data } = await getPmsReceiveDetailPage({
      ...query,
      ...page,
      confirmFlag: 0, // 查询未确认的
    });
    detailTableData.value = data.list;
    detailTableTotal.value = data.total;
    detailTableLoading.value = false;
  };

  const deleteDetail = async (row) => {
    await info({
      title: '删除确认',
      content: '您确定要删除当前所选的数据？',
      okText: '确认',
    });
    const { id } = row;
    await deletePmsReceiveDetail(id);
    Message.success({
      content: '删除成功！',
      duration: 5 * 1000,
    });
    getDetailTableList();
  };
  const addDetail = () => {
    selectOrderModelVisible.value = true;
  };

  // box-list
  const boxTable = ref(null);
  const boxSelectedKeys = ref([]);
  const boxTableData = ref([]);
  const boxTableTotal = ref(0);
  const boxTableLoading = ref(false);
  const boxSelectionChange = (rowKeys: (string | number)[]) => {
    if (rowKeys && rowKeys.length) {
      boxSelectRowList = rowKeys;
      // const [selectId] = boxSelectRowList;
      // selectBoxId.value = selectId;
    }
  };
  const boxPageChange = () => {
    getBoxTableList();
  };
  const boxPageSizeChange = () => {
    getBoxTableList();
  };

  const getBoxTableList = async () => {
    const query = boxTable.value.getStatus();
    query.pmsReceiveId = selectId?.value;
    try {
      boxTableLoading.value = true;
      const { data } = await getPmsReceiveBoxPage(query);
      boxTableData.value = data.list;
      boxTableTotal.value = data.total;
      if (
        hasDataAndBack(
          boxTableData.value,
          boxTableTotal.value,
          boxTable.value?.getStatus().pageNo
        )
      ) {
        boxTable.value?.setCurrent(boxTable.value.getStatus().pageNo - 1);
        getBoxTableList();
      }
    } finally {
      boxTableLoading.value = false;
    }
  };
  const deleteBox = async (row) => {
    await info({
      title: '删除确认',
      content: '您确定要删除当前所选的数据？',
      okText: '确认',
    });
    const { id } = row;
    await deletePmsReceiveBox(id);
    Message.success({
      content: '删除成功！',
      duration: 5 * 1000,
    });
    getBoxTableList();
  };
  const init = () => {};
  init();
</script>

<style lang="less" scoped>
  @import url('../moduleCommon/common.less');
</style>
